//
//  FundPwdViewController.m
//  Learn
//
//  Created by zyl_macbookpro on 2024/3/30.
//  Copyright © 2024 迟建国. All rights reserved.
//

#import "FundPwdViewController.h"
#import "LoginAPIManager.h"
#import "LoginHistoryAccountView.h"
#import "SelectedSchoolController.h"
@interface FundPwdViewController ()<UITextFieldDelegate ,UITableViewDelegate,UITableViewDataSource>

@property(nonatomic ,strong)UITableView *tableView;

@property(nonatomic ,strong)UIView *tableHeaderView;

@property(nonatomic ,strong)UIView *tableFootorView;

@property(nonatomic ,strong)UIButton *confirmButton;

@property(nonatomic ,strong)UITextField *accountTextFiled;

@property(nonatomic ,strong)UITextField *veriftyTextFiled;

@property(nonatomic ,strong)UITextField *phoneVeriftyFiled;

@property(nonatomic ,strong)UITextField *passwordTextFiled;

@property(nonatomic ,strong)WKWebView *captchaWeb;

@property(nonatomic ,strong)NSMutableURLRequest *captchaRequest;

@property(nonatomic ,copy)NSString *captcha_token;

@property (nonatomic, strong) UIButton *sendCodeBtn;

@property (nonatomic, strong) NSTimer *captchaTimer;

@property (nonatomic, assign) NSInteger captchaCountDownSeconds;
@end

@implementation FundPwdViewController
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    [self renderNavBarWithBackgroundImage:[UIImage imageWithColor:lWhiteColor] backgroundColor:nil shadowColor:nil textAttributeDic:@{NSForegroundColorAttributeName:rgba(51, 51, 51, 1),NSFontAttributeName:MFontWithSize(18)} enableScrollEdgeAppearance:YES];

}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = YES;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"找回密码";
    [self.view addSubview:self.tableView];
    [BaseRequest checkoutNetWorkStatus:^(AFNetworkReachabilityStatus status) {
        if (status == AFNetworkReachabilityStatusReachableViaWiFi || status == AFNetworkReachabilityStatusReachableViaWWAN) {
            [self.captchaWeb loadRequest:self.captchaRequest];
        }
    }];
    
    self.captchaCountDownSeconds = 60;
}
#pragma mark -API
- (void)sendMsg
{
    NSDictionary *dic = @{@"mobile":self.accountTextFiled.text,@"event":@"resetpwd"};
    [LoginAPIManager SendSMSWithParam:dic result:^(NSDictionary * _Nonnull dic) {
        [self startTimer];
    }];
}
- (void)changePwd
{
    NSDictionary *dic = @{@"mobile":self.accountTextFiled.text,@"captcha_token":self.captcha_token,@"captcha":self.veriftyTextFiled.text,@"mobile_captcha":self.phoneVeriftyFiled.text,@"newpassword":self.passwordTextFiled.text};
    [LoginAPIManager FoundPwdWithParam:dic result:^(NSDictionary * _Nonnull dic) {

       if ([dic[@"code"] intValue] != 1) {
           [self reloadWeb];
           [SVProgressHUD showImage:nil status:dic[@"msg"]];
           return;
       }
        [self.navigationController popViewControllerAnimated:YES];
    }];
}
#pragma mark -UITableViewDelegate,UITableViewDelegate
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell =nil;
    
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];
        cell.selectionStyle =UITableViewCellSelectionStyleNone;
    }
    [cell.contentView removeAllSubviews];
  
      if(indexPath.row == 0)
      {
          [cell.contentView addSubview:self.accountTextFiled];
          
      }else if (indexPath.row == 1)
      {
          [cell.contentView addSubview:self.veriftyTextFiled];
      }else if (indexPath.row == 2)
      {
          [cell.contentView addSubview:self.phoneVeriftyFiled];
          
      }else{
          
          [cell.contentView addSubview:self.passwordTextFiled];
          
      }
       
  
    
    return cell;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
        return 4;
        
  
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    return 62;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{


}



#pragma mark -UITextFieldDelegate
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    //[[textField viewWithTag:1001] setBackgroundColor:kOrangeLineColor];
}

-(BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    //[[textField viewWithTag:1001] setBackgroundColor:kLineColor];
    
    return  YES;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    return YES;
}
#pragma mark - private
- (void)startTimer
{
    self.sendCodeBtn.enabled = NO;
    [self.captchaTimer fire];
}

- (void)resetTimer
{
    if (self.captchaTimer) {
        self.captchaCountDownSeconds =60;
        [self.captchaTimer invalidate];
        self.captchaTimer =nil;
        
        self.sendCodeBtn.enabled =YES;
        [self.sendCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    }
}
#pragma mark -event response

- (void)tapClick
{
    [self.view endEditing:YES];
}
-(void)oneMinutCutdown:(NSTimer *)aTimer
{
    self.captchaCountDownSeconds--;
    [self.sendCodeBtn setTitle:[NSString stringWithFormat:@"%ld秒重新发送",self.captchaCountDownSeconds] forState:UIControlStateNormal];
    
    //当计时器为0时，关闭计时器
    if (self.captchaCountDownSeconds ==0)
    {
        [self resetTimer];
    }
}


- (void)confirmButtonAction
{

    [self.view endEditing:YES];
    NSString *str = @"";
    if (self.accountTextFiled.text.length == 0) {
        str = @"手机号不能为空！";
    }
    
    if (self.veriftyTextFiled.text.length == 0) {
        str = @"验证码不能为空！";
    }
    
    if (self.phoneVeriftyFiled.text.length == 0) {
        str = @"手机验证码不能为空！";
    }
    
    if (self.passwordTextFiled.text.length == 0) {
        str = @"密码不能为空！";
    }
    
    if (str.length == 0) {
        [MethodTool getCookieWithwebView:self.captchaWeb success:^(BOOL success) {
            [self changePwd];
        }];
    }else{
        [SVProgressHUD showImage:nil status:str];
    }
    
}
- (void)sendCodeBtnClick
{
    [self sendMsg];

}

-(void)reloadWeb
{
    [self.view endEditing:YES];
    [self.captchaWeb loadRequest:self.captchaRequest];
}


-(void)textFieldResignTapAction:(UITapGestureRecognizer *)sender
{
    [self.view endEditing:YES];
}
-(void)textEnd:(UITextField *)textField
{
    [self.tableView reloadData];
}
-(void)textChanged:(UITextField *)textField
{
    
}
#pragma mark -getters and setters
-(UITableView *)tableView{
    if (!_tableView){
        _tableView =[[UITableView alloc] initWithFrame:CGRectMake(0, 0, lScreenWidth, lScreenHeight) style:UITableViewStylePlain];
        [_tableView setDelegate:self];
        [_tableView setDataSource:self];
        _tableView.bounces = NO;
        [_tableView setBackgroundColor:lWhiteColor];
        [_tableView setSeparatorColor:rgba(229, 229, 229, 1)];
        _tableView.separatorInset = UIEdgeInsetsMake(0, 20, 0, 20);
        [_tableView setTableHeaderView:self.tableHeaderView];
        [_tableView setTableFooterView:self.tableFootorView];
    }
    
    return _tableView;
}

-(UIView *)tableHeaderView
{
    if (!_tableHeaderView)
    {
        
        _tableHeaderView =[[UIView alloc] initWithFrame:CGRectMake(0, 0, lScreenWidth,76)];
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick)];
            [_tableHeaderView addGestureRecognizer:tap];
        UIView *viewbg = [[UIView alloc] init];
        viewbg.frame = CGRectMake(0,0,lScreenWidth,36);
        viewbg.backgroundColor = rgba(216, 241, 230, 1);
        [_tableHeaderView addSubview:viewbg];
        
        UIButton *titleLBtn = ({
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake( 15, 0, (lScreenWidth - 60 - 15)/2.0, 36);
            [button setTitle:@"请输入已绑定的手机号" forState:UIControlStateNormal];
            button.titleLabel.font = MFontWithSize(14.f);
            [button setTitleColor:rgba(12, 183, 108, 1) forState:UIControlStateNormal];
            [button setImage:IMAGENAMED(@"ic_warn") forState:UIControlStateNormal];
            button;
        });
        double w = [MethodTool getTextWidthWithStr:titleLBtn.titleLabel.text font:titleLBtn.titleLabel.font ViewHeight:36];
        titleLBtn.width = w + 10 + 16;
        titleLBtn.centerX = viewbg.centerX;
        [titleLBtn layoutButtonWithEdgeInsetsStyle:LButtonEdgeInsetsStyleLeft imageTitleSpace:10];
        [_tableHeaderView addSubview:titleLBtn];
       
       
    }
    
    return _tableHeaderView;
}

-(UIView *)tableFootorView
{
    if (!_tableFootorView)
    {
        _tableFootorView =[[UIView alloc] initWithFrame:CGRectMake(0, 0, lScreenWidth - 20, 20)];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick)];
        [_tableFootorView addGestureRecognizer:tap];
        UIView *loginView =[[UIView alloc] initWithFrame:CGRectMake(20, 65, lScreenWidth - 40, 45)];
        [loginView setAllCornersWithCornerRadius:22.5];
        // gradient
        CAGradientLayer *gl = [CAGradientLayer layer];
        gl.frame = CGRectMake(0,0,lScreenWidth - 40,45);
        gl.startPoint = CGPointMake(1, 0.5);
        gl.endPoint = CGPointMake(0, 0.5);
        gl.colors = @[(__bridge id)[UIColor colorWithRed:41/255.0 green:241/255.0 blue:156/255.0 alpha:1.0].CGColor, (__bridge id)[UIColor colorWithRed:2/255.0 green:161/255.0 blue:249/255.0 alpha:1.0].CGColor];
        gl.locations = @[@(0), @(1.0f)];
        [loginView.layer addSublayer:gl];
        [loginView addSubview:self.confirmButton];
       
        [_tableFootorView addSubview:loginView];
        _tableFootorView.height =loginView.bottom + 15;
    }
    
    return _tableFootorView;
}


-(UIButton *)confirmButton
{
    if (!_confirmButton)
    {
        _confirmButton = [UIButton new];
        _confirmButton.frame =CGRectMake(0, 0, lScreenWidth - 40, 45);
       
        [_confirmButton setTitle:@"确定" forState:UIControlStateNormal];
       // [_confirmButton setTitleColor:rgba(181, 181, 181, 1) forState:UIControlStateNormal];
        [_confirmButton setTitleColor:lWhiteColor forState:UIControlStateNormal];
        [_confirmButton.titleLabel setFont:MFontWithSize(18)];
        [_confirmButton addTarget:self action:@selector(confirmButtonAction) forControlEvents:UIControlEventTouchUpInside];
        
    }
    
    return _confirmButton;
}
-(UITextField *)phoneVeriftyFiled
{
    if (!_phoneVeriftyFiled)
    {
        _phoneVeriftyFiled =[[UITextField alloc] initWithFrame:CGRectMake(20, 0, lScreenWidth - 40, 62)];
        _phoneVeriftyFiled.font = MFontWithSize(16);
        _phoneVeriftyFiled.textColor = rgba(51, 51, 51, 1);
        _phoneVeriftyFiled.clearButtonMode =UITextFieldViewModeWhileEditing;
        _phoneVeriftyFiled.attributedPlaceholder = [[NSMutableAttributedString alloc] initWithString:@"请输入手机验证码" attributes:@{NSFontAttributeName:MFontWithSize(16)}];
        _phoneVeriftyFiled.delegate =self;
        if (@available(iOS 11.0,*)) {
            _phoneVeriftyFiled.textContentType =UITextContentTypeUsername;
        }
        [_phoneVeriftyFiled addTarget:self action:@selector(textEnd:) forControlEvents:UIControlEventEditingDidEnd];
        [_phoneVeriftyFiled addTarget:self action:@selector(textChanged:) forControlEvents:UIControlEventEditingChanged];
        
        UIView *rightSpaceView = [[UIView alloc] init];
        rightSpaceView.frame = CGRectMake(0,0,100,62);
        [rightSpaceView addSubview:self.sendCodeBtn];
        [rightSpaceView addSubview:separateLineWithColor(CGRectMake(0, 24, 1, 15), rgba(229, 229, 229, 1))];
        _phoneVeriftyFiled.rightViewMode = UITextFieldViewModeAlways;
        _phoneVeriftyFiled.rightView = rightSpaceView;
    }

    return _phoneVeriftyFiled;
}

-(UITextField *)veriftyTextFiled
{
    if (!_veriftyTextFiled)
    {
        _veriftyTextFiled =[[UITextField alloc] initWithFrame:CGRectMake(20, 0, lScreenWidth - 40, 62)];
        _veriftyTextFiled.font = MFontWithSize(16);
        _veriftyTextFiled.textColor = rgba(51, 51, 51, 1);
        _veriftyTextFiled.clearButtonMode =UITextFieldViewModeWhileEditing;
        _veriftyTextFiled.attributedPlaceholder = [[NSMutableAttributedString alloc] initWithString:@"请输入验证码" attributes:@{NSFontAttributeName:MFontWithSize(16)}];
        _veriftyTextFiled.delegate =self;
       
        if (@available(iOS 11.0,*)) {
            _veriftyTextFiled.textContentType =UITextContentTypeUsername;
        }
      
        [_veriftyTextFiled addTarget:self action:@selector(textChanged:) forControlEvents:UIControlEventEditingChanged];
        UIView *rightSpaceView = [[UIView alloc] init];
        rightSpaceView.frame = CGRectMake(0,0,120,62);
        [rightSpaceView addSubview:self.captchaWeb];
        [self.captchaWeb loadRequest:self.captchaRequest];
        [rightSpaceView addSubview:self.captchaWeb];
        UIButton *relodBtn = [UIButton new];
        relodBtn.frame = CGRectMake(0,0,120,62);;
        [rightSpaceView addSubview:relodBtn];
        [relodBtn addTarget:self action:@selector(reloadWeb) forControlEvents:UIControlEventTouchUpInside];
        _veriftyTextFiled.rightViewMode = UITextFieldViewModeAlways;
        _veriftyTextFiled.rightView = rightSpaceView;
        
    }

    return _veriftyTextFiled;
}
- (WKWebView *)captchaWeb
{
    if(!_captchaWeb)
    {
        _captchaWeb = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, 120, 62)];
        
    }
    return _captchaWeb;
}
- (NSMutableURLRequest *)captchaRequest
{
   
    self.captcha_token =  [NSString stringWithFormat:@"%d",arc4random()];
    NSString *url = [NSString stringWithFormat:@"%@%@%@%@",BaseUrl,KM_API_User_Login_Captcha_Url,@"?id=",self.captcha_token];
    return [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
}
-(UITextField *)accountTextFiled
{
    if (!_accountTextFiled)
    {
        _accountTextFiled =[[UITextField alloc] initWithFrame:CGRectMake(20, 0, lScreenWidth - 40, 62)];
        _accountTextFiled.font = MFontWithSize(16);
        _accountTextFiled.textColor = rgba(51, 51, 51, 1);
        _accountTextFiled.clearButtonMode =UITextFieldViewModeWhileEditing;
        _accountTextFiled.attributedPlaceholder = [[NSMutableAttributedString alloc] initWithString:@"请输入父母或者自己的手机号" attributes:@{NSFontAttributeName:MFontWithSize(16)}];
        _accountTextFiled.delegate =self;
       // [_accountTextFiled setInputAccessoryView:self.customTextFieldInputAccessoryView];
        if (@available(iOS 11.0,*)) {
            _accountTextFiled.textContentType =UITextContentTypeUsername;
        }
      
      
    }

    return _accountTextFiled;
}
-(UITextField *)passwordTextFiled
{
    if (!_passwordTextFiled)
    {
        _passwordTextFiled =[[UITextField alloc] initWithFrame:CGRectMake(20, 0, lScreenWidth - 40, 62)];
        _passwordTextFiled.font = MFontWithSize(16);
        _passwordTextFiled.textColor = rgba(51, 51, 51, 1);
        _passwordTextFiled.clearButtonMode =UITextFieldViewModeWhileEditing;
        _passwordTextFiled.secureTextEntry =YES;
        _passwordTextFiled.delegate =self;
        _passwordTextFiled.placeholder = @"请输入密码";
        

        if (@available(iOS 11.0,*)) {
            _passwordTextFiled.textContentType =UITextContentTypePassword;
        }
    
    }

    return _passwordTextFiled;
}
- (UIButton *)sendCodeBtn
{
    if (!_sendCodeBtn) {
        _sendCodeBtn =[UIButton buttonWithType:UIButtonTypeCustom];
        _sendCodeBtn.titleLabel.font = RFontWithSize(16);
        [_sendCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        [_sendCodeBtn setTitleColor:rgba(12, 183, 108, 1) forState:UIControlStateNormal];
        [_sendCodeBtn setTitleColor:rgba(181, 181, 181, 1) forState:UIControlStateDisabled];
        [_sendCodeBtn addTarget:self action:@selector(sendCodeBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [_sendCodeBtn setFrame:CGRectMake(1, 0, 100, 62)];
    }
    
    return _sendCodeBtn;
}
-(NSTimer *)captchaTimer
{
    if (!_captchaTimer)
    {
        _captchaTimer =[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(oneMinutCutdown:) userInfo:nil repeats:YES];
    }
    
    return _captchaTimer;
}
@end
